package br.com.foxinline.manager.itbi;

import br.com.foxinline.enums.TipoFinanciamento;
import br.com.foxinline.enums.TipoTransmissao;
import br.com.foxinline.modelo.ConfigItbi;
import br.com.foxinline.modelo.Imovel;
import br.com.foxinline.modelo.Itbi;
import br.com.foxinline.servico.AverbacaoServico;
import br.com.foxinline.servico.ConfigItbiServico;
import br.com.foxinline.servico.ImovelServico;
import br.com.foxinline.servico.IptuServico;
import br.com.foxinline.servico.ItbiServico;
import br.com.foxinline.util.Msg;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

/**
 *
 * @author nayra
 */
@ManagedBean
@ViewScoped
public class ManagerItbi {

    @EJB
    private ItbiServico itbiServico;
    @EJB
    private ImovelServico imovelServico;
    @EJB
    private AverbacaoServico averbacaoServico;
    @EJB
    private ConfigItbiServico configItbiServico;
    @EJB
    private IptuServico iptuServico;
    private int tabActive;
    private Itbi itbi;
    private String imovelId;
    private Imovel imovel;
    private String inscCadastral;
    private List<Itbi> itbis;
    private Itbi itbiRemocao;
    private boolean visualizacao;

    @PostConstruct
    public void init() {
        tabActive = 0;
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        imovelId = params.get("imovelId");
        imovel = imovelServico.find(Long.parseLong(imovelId));
        initItbi();
        itbis = itbiServico.findByImovel(imovelId);
    }

    public void vlrEdificacao() {
        BigDecimal fatorDepreciacao = itbi.getFatorDepreciacaoEdificacao();
        BigDecimal vlrM2Edificacao = itbi.getVlrM2ReaisEdificacao();

        if (fatorDepreciacao == null) {
            fatorDepreciacao = BigDecimal.ONE;
        }
        if (vlrM2Edificacao == null) {
            vlrM2Edificacao = BigDecimal.ONE;
        }

        BigDecimal vlrEdificacao = itbi.getM2AreaEdificacao().multiply(vlrM2Edificacao).multiply(fatorDepreciacao).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
        itbi.setVlrEdificacao(vlrEdificacao);
        vlrImovel();
        vlrTotal();
    }

    private void vlrImovel() {
        itbi.setVlrImovel(itbi.getVlrEdificacao().add(itbi.getVlrTerreno()));
        itbi.setVlrImovel(itbi.getVlrImovel().divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP));
    }

    private void vlrTotal() {
        itbi.setValor(itbi.getAliquota().multiply(itbi.getVlrImovel()).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP));
    }

    public void vlrAliquota() {
        ConfigItbi configItbi = configItbiServico.findAll().get(0);

        if (itbi.getTipoFinanciamento() == TipoFinanciamento.DEMAIS_TRANSMISSOES) {
            itbi.setAliquota(configItbi.getAliquota().divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP));
        } else {
            itbi.setAliquota(configItbi.getAliquotaInstFinan().divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP));
        }
    }

    public void remover() {
        this.itbis.remove(itbiRemocao);
        itbiServico.delete(itbiRemocao);
    }

    public void gerarItbi() {
        if (iptuServico.findIptuNaoPagos(itbi.getImovel().getId()).isEmpty()) {
            try {
                itbiServico.gerarItbi(itbi);
            } catch (Exception ex) {
                Msg.messagemWarn(ex.getMessage());
            }
            Msg.messagemInfo(Msg.SuccessFull);
            visualizacao = true;
            itbis = itbiServico.findByImovel(imovelId);
        } else {
            Msg.messagemWarn("Operação não realizada! O imóvel possue IPTU(s) para pagamento. Regularize a situação antes!");
        }
    }

    public void tabVisualizacao() {
        tabActive = 1;
        visualizacao = true;
    }

    public void boleto() {
        itbiServico.gerarGuia(itbi);
    }

    public boolean validaGeracaoItbi(Itbi itbi) {
        if (itbi.getProprietario() != null && itbi.getDataVencimento() != null && itbi.getM2AreaEdificacao() != null
                && itbi.getM2AreaTerreno() != null && itbi.getVlrM2ReaisEdificacao() != null && itbi.getVlrM2UfmpTerreno() != null
                && itbi.getVlrEdificacao() != null && itbi.getVlrTerreno() != null) {
            return true;
        } else {
            Msg.messagemError("Preencha Corretamente os campos!");
            return false;
        }
    }

    private void initImovel() {
        itbi.setProprietario(imovelServico.lstProprietario(itbi.getImovel()).get(0));
        vlrAliquota();
        DecimalFormat d = new DecimalFormat("");
        d.setMinimumIntegerDigits(2);
        inscCadastral += d.format(itbi.getImovel().getInscricaoCadastralD() == null ? 0 : itbi.getImovel().getInscricaoCadastralD());
        inscCadastral += d.format(itbi.getImovel().getInscricaoCadastralS() == null ? 0 : itbi.getImovel().getInscricaoCadastralS());
        d.setMinimumIntegerDigits(3);
        inscCadastral += d.format(itbi.getImovel().getInscricaoCadastralQuadra() == null ? 0 : itbi.getImovel().getInscricaoCadastralQuadra());
        d.setMinimumIntegerDigits(4);
        d.setDecimalSeparatorAlwaysShown(false);
        inscCadastral += d.format(itbi.getImovel().getInscricaoCadastralLote() == null ? 0 : itbi.getImovel().getInscricaoCadastralLote());
        d.setMinimumIntegerDigits(2);
        inscCadastral += d.format(itbi.getImovel().getInscricaoCadastralUnid() == null ? 0 : itbi.getImovel().getInscricaoCadastralUnid());
    }

    public void initItbi() {
        this.itbi = itbiServico.initItbi(imovel);
        initImovel();
        this.visualizacao = false;
    }

    public List<SelectItem> getTipoTransmissoes() {
        List<SelectItem> list = new ArrayList<SelectItem>();
        for (TipoTransmissao tipoTransmissao : TipoTransmissao.values()) {
            list.add(new SelectItem(tipoTransmissao, tipoTransmissao.getNome()));
        }
        return list;
    }

    public List<SelectItem> getTipoFinanciamentos() {
        List<SelectItem> list = new ArrayList<SelectItem>();
        for (TipoFinanciamento tipoFinanciamento : TipoFinanciamento.values()) {
            list.add(new SelectItem(tipoFinanciamento, tipoFinanciamento.getNome()));
        }
        return list;
    }

    public String proprietarios(Imovel imovel) {
        return averbacaoServico.getNomeProprietarios(imovel.getProprietarios());
    }

    public String getImovelId() {
        return imovelId;
    }

    public void setImovelId(String imovelId) {
        this.imovelId = imovelId;
    }

    public String getInscCadastral() {
        return inscCadastral;
    }

    public void setInscCadastral(String inscCadastral) {
        this.inscCadastral = inscCadastral;
    }

    public Itbi getItbi() {
        return itbi;
    }

    public void setItbi(Itbi itbi) {
        this.itbi = itbi;
    }

    public List<Itbi> getItbis() {
        return itbis;
    }

    public void setItbis(List<Itbi> itbis) {
        this.itbis = itbis;
    }

    public Itbi getItbiRemocao() {
        return itbiRemocao;
    }

    public void setItbiRemocao(Itbi itbiRemocao) {
        this.itbiRemocao = itbiRemocao;
    }

    public Imovel getImovel() {
        return imovel;
    }

    public void setImovel(Imovel imovel) {
        this.imovel = imovel;
    }

    public int getTabActive() {
        return tabActive;
    }

    public void setTabActive(int tabActive) {
        this.tabActive = tabActive;
    }

    public boolean isVisualizacao() {
        return visualizacao;
    }

    public void setVisualizacao(boolean visualizacao) {
        this.visualizacao = visualizacao;
    }
}